#include "mywidget.h"
#include "ui_mywidget.h"
#include<QHostAddress>
#include<QFileDialog>
#include<QFileInfo>
#include<QMessageBox>
#include<QDebug>

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyWidget)
{
    ui->setupUi(this);

    setWindowTitle("端口号为：8888");

    ui->buttonselect->setEnabled(true);
    ui->buttonfile->setEnabled(false);

    udpsocket = new QUdpSocket(this);

    //udpsocket->bind(8888);
    udpsocket->bind(QHostAddress::AnyIPv4,8888,QUdpSocket::ShareAddress);

    //加入D类组播
    udpsocket->joinMulticastGroup(QHostAddress("224.0.0.2"));

    isstart=true;

    connect(udpsocket,&QUdpSocket::readyRead,this,&MyWidget::dealmsg);

    connect(&timer,&QTimer::timeout,
            [=]()
    {
        //关闭定时器
        timer.stop();

        //发送文件
        sendata();
    }

     );
}

MyWidget::~MyWidget()
{
    delete ui;
}

void MyWidget::dealmsg()
{
    char buf[1024*4] = {0};
    QHostAddress addr;
    quint16 port;
    qint64 len = udpsocket->readDatagram(buf,sizeof(buf),&addr,&port);

    qDebug()<<len;

    if(len>0)
    {
        isfile = QString(buf).section("##",0,0);
        if(isfile == "text")
        {
            QString text =QString(buf).section("##",1,1);
            QString str = QString("[%1:%2] %3").arg(addr.toString()).arg(port).arg(text);

            ui->textEditread->append(str);

        }
        else
        {

            if(true == isstart)//第一次发的头，接收头
            {
                isstart = false;

                //取出接收的内容(拆包)
                filename = QString(buf).section("##",1,1);
                qDebug()<<filename;
                filesize = QString(buf).section("##",2,2).toInt();
                qDebug()<<filesize;
                //开始收到的文件大小为0
                receivesize=0;

                //打开文件
                file.setFileName(filename);
                bool isok=file.open(QIODevice::WriteOnly);

                qDebug()<<isok;

                if(false == isok)
                {
                    qDebug()<<"writeonly error";

 //                   udpsocket->close();

 //                   return;//如果打开文件失败，中断连接
                 }
             }
             else//取出文件数据
             {
                //qDebug()<<"取出数据";
                qint64 lenth=file.write(buf,sizeof(buf));
                //qDebug()<<lenth;
                receivesize +=lenth;
                //qDebug()<<receivesize;
                if(receivesize==filesize)
                {
                    //udpsocket->writeDatagram("file done");
                    QMessageBox::information(this,"完成","文件接受完成！");

                    udpsocket->close();

                 }

//                char buff[1024*4] = {0};
//                qint64 lenth=0;
//                do{
//                    udpsocket->readDatagram(buff,sizeof(buff),&addr,&port);
//                    qDebug()<<"我在这里";
//                    lenth = file.write(buff);
//                    qDebug()<<lenth;

//                    receivesize += lenth;

//                    if(receivesize==filesize)//文件接受完成
//                    {
//                        //给服务器发送接收完成信息
//                        //ui->textEditread->append("文件接收完成");

//                        QMessageBox::information(this,"完成","文件接受完成！");

//                        file.close();//关闭文件
//                    }
//                }while(lenth > 0);

             }

        }

    }

}


void MyWidget::on_buttonsend_clicked()
{
    QString ip = ui->lineEditip->text();
    quint16 port = ui->lineEditport->text().toInt();

    if(ip.isEmpty()==false)
    {
        QString text = ui->textEditwrite->toPlainText();
        QString str = QString("text##%1").arg(text);
        udpsocket->writeDatagram(str.toUtf8(),QHostAddress("224.0.0.2"),port);
    }

}

bool isconnect=true;

void MyWidget::on_buttonclose_clicked()
{
    if(isconnect==true)
    {
        udpsocket->close();
        ui->buttonclose->setText("重新连接");
        isconnect = false;
    }
    else{
        udpsocket = new QUdpSocket(this);

        udpsocket->bind(9000);

        connect(udpsocket,&QUdpSocket::readyRead,this,&MyWidget::dealmsg);

        ui->buttonclose->setText("close");
        isconnect=true;
    }


}

void MyWidget::on_buttonselect_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this,"open","../");
    if(false == filePath.isEmpty())//选择路径有效
    {
        filename.clear();
        filesize = 0;

        //获取文件信息
        QFileInfo info(filePath);
        filename = info.fileName();
        filesize = info.size();

        sendsize=0;
        //sendsize=0;
        //只读方式打开文件
        //指定文件名字
        file.setFileName(filePath);

        //打开文件
        bool isok = file.open(QIODevice::ReadOnly);
        if(false == isok)
        {
            qDebug()<<"只读方式打开文件失败 98";
        }

        //提示打开的文件路径
        ui->textEditwrite->setText(filePath);

        ui->buttonselect->setEnabled(false);
        ui->buttonfile ->setEnabled(true);
    }
    else{
        qDebug()<<"选择文件路径出错";
    }
}

void MyWidget::on_buttonfile_clicked()
{
    //先发送文件头信息  文件名##文件大小
    QString head = QString("file##%1##%2").arg(filename).arg(filesize);

    QString ip = ui->lineEditip->text();
    quint16 port = ui->lineEditport->text().toInt();

    qint64 len = udpsocket->writeDatagram(head.toUtf8(),QHostAddress("224.0.0.2"),port);

    qDebug()<<len;

    if(len > 0)//头部信息发送成功
    {
        timer.start(20);
 //       sendata();
    }
    else
    {
        qDebug()<<"头部信息发送失败";
        file.close();
    }
    ui->buttonselect->setEnabled(true);
    ui->buttonfile->setEnabled(false);
}

void MyWidget::sendata()
{
    qint64 lenth=0;
    //sendsize=0;
    do
    {
        //每次发送数据的大小
        char buf[4*1024]={0};
        lenth=0;

        QString ip = ui->lineEditip->text();
        quint16 port = ui->lineEditport->text().toInt();

        //往文件中读数据
        lenth = file.read(buf,sizeof(buf));
        //发送数据，读多少发多少
        lenth = udpsocket->writeDatagram(QByteArray(buf),QHostAddress("224.0.0.2"),port);

        //qDebug()<<lenth;
        //发送数据需要累加
        sendsize += lenth;
        qDebug()<<sendsize;
    }while(lenth > 0);

    //是否文件发送完毕
    if(sendsize==filesize)//file.atEnd())
    {
        ui->textEditread->append("文件发送完毕");
        file.close();
    }
}
